package cn.lf.service.impl;
import com.google.common.collect.Lists;

import cn.lf.constant.DelFlagTypeEnum;
import cn.lf.dto.api.product.IndexProductInfoRepDTO;
import cn.lf.dto.api.product.IndexProductInfoReqDTO;
import cn.lf.dto.api.product.ShopProductInfoRepDTO;
import cn.lf.entity.ProductType;
import cn.lf.mapper.ProductMapper;
import cn.lf.mapper.ProductTypeMapper;
import cn.lf.service.ApiProductService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ApiProductServiceImpl implements ApiProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductTypeMapper productTypeMapper;


    @Override
    public IPage<IndexProductInfoRepDTO> getIndexProductInfo(IndexProductInfoReqDTO params) {

        Page<IndexProductInfoRepDTO> page = new Page<>(params.getCurrentPage(),params.getPageSize());

        return productMapper.getIndexProductInfo(page,params);
    }

    @Override
    public List<ShopProductInfoRepDTO> getShopProductInfoList(String shopId) {

        List<ShopProductInfoRepDTO> list = new ArrayList<>();

        LambdaQueryWrapper<ProductType> ptQueryWrapper = new LambdaQueryWrapper<>();

        ptQueryWrapper.eq(ProductType::getDelFlag, DelFlagTypeEnum.UN_DEL.getCode());

        ptQueryWrapper.eq(ProductType::getShopId, shopId);

        List<ProductType> productTypeList = productTypeMapper.selectList(ptQueryWrapper);

        List<ShopProductInfoRepDTO.ProductInfo> allProductInfo = productMapper.selectShopProductInfo(shopId);

        for (ProductType productType : productTypeList) {

            ShopProductInfoRepDTO temp = new ShopProductInfoRepDTO();
            temp.setProductTypeId(productType.getProductTypeId());
            temp.setProductTypeName(productType.getProductTypeName());

            List<ShopProductInfoRepDTO.ProductInfo> productInfoList =
                    allProductInfo.stream().filter(v -> Objects.equals(v.getProductTypeId(),temp.getProductTypeId()))
                            .sorted(Comparator.comparing(ShopProductInfoRepDTO.ProductInfo::getSort))
                            .collect(Collectors.toList());

            temp.setProductInfoList(productInfoList);

            list.add(temp);
        }

        return list;
    }
}
